package com.peng.sell.controller;

import com.peng.sell.vo.ServerResponseVO;
import com.peng.sell.dataobject.ProductCategory;
import com.peng.sell.dataobject.ProductInfo;
import com.peng.sell.service.ProductCategoryService;
import com.peng.sell.service.ProductInfoService;
import com.peng.sell.vo.ProductInfoVO;
import com.peng.sell.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
@CacheConfig(cacheNames = "product")
public class BuyerProductController {
    @Autowired
    ProductInfoService productInfoService;
    @Autowired
    ProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Cacheable(key = "'list'")
    public ServerResponseVO list() {
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        List<Integer> categoryIds = productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> categoryList = productCategoryService.findProductCategoryByCategoryTypeIn(categoryIds);
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory category : categoryList){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(category.getCategoryName());
            productVO.setCategoryType(category.getCategoryType());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList){
                if(productInfo.getCategoryType()==category.getCategoryType()){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        if(productVOList.size()>0){
            return ServerResponseVO.createBySuccess("获取数据成功",productVOList);
        }
        return ServerResponseVO.createByErrorMsg("获取数据失败");

    }

}
